//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Copyright 2012 Microsoft Corporation. All Rights Reserved
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.   
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Copyright 2012 Microsoft Corporation. All Rights Reserved
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.   
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

namespace Preflight.Core
{
    using System;
    using System.Configuration;

    public abstract class ConfigurationSectionReaderBase<TConfigSection> where TConfigSection : PreflightConfigurationSectionBase 
    {
        protected abstract string ConfigurationSectionPath
        {
            get;
        }

        public bool ConfigurationExists()
        {
            try
            {
                return this.GetSection() != null;
            }
            catch (PreflightConfigurationNotFoundException)
            {
                return false;
            }
        }

        protected TConfigSection GetSection()
        {
            Log.LogVerbose("Loading configuration section: {0}", this.ConfigurationSectionPath);
            TConfigSection section = null;
            try
            {
                section = ConfigurationManager.GetSection(this.ConfigurationSectionPath) as TConfigSection;
            }
            catch (Exception exception)
            {
                Log.LogError("Loading configuration section failed with this exception: {0}. Section: {1}", exception, this.ConfigurationSectionPath);
                throw new FailedToLoadEngineConfigurationException(exception);
            }

            if (section != null)
            {
                Log.LogVerbose("Section {0} loaded!", this.ConfigurationSectionPath);
            }
            else
            {
                Log.LogError("No configuration section found at: {0}", this.ConfigurationSectionPath);
                throw new PreflightConfigurationNotFoundException();
            }

            return section;
        }

        protected TInstance CreateInstanceFromConfiguredTypeName<TInstance>(TConfigSection section, string propertyName) where TInstance : class
        {
            var typeName = section.GetValue<string>(propertyName);
            var targetTypeName = typeof(TInstance).FullName;
            Log.LogInformation("Attempting to load: {0}", typeName);
            var type = Type.GetType(typeName);
            if (type == null)
            {
                throw new InvalidOperationException("Could not load type: " + typeName);
            }

            Log.LogVerbose("Loaded type: {0}", type.FullName);

            Log.LogVerbose("Creating an instance of {0}", type.FullName);
            var instance = Activator.CreateInstance(type);
            var instanceTypeName = instance.GetType().FullName;
            Log.LogVerbose("Successfull created an instance of {0}", instanceTypeName);

            Log.LogVerbose("Checking if instance can be cast as {0}", targetTypeName);

            var instanceFromConfiguredTypeName = instance as TInstance;
            if (instanceFromConfiguredTypeName == null)
            {
                Log.LogError("Type {0} loaded but it cannot be cast to {1}", instanceTypeName, targetTypeName);
            }

            Log.LogInformation("{0} successfully loaded", instanceTypeName);
            return instanceFromConfiguredTypeName;
        }
    }
}
